<?php
class XxAction extends BaseAction{
    public function _initialize(){ //初始化接口  // 回调方法 初始化模型
        parent::_initialize();
    }
	
	public function home(){
		$userid=$_SESSION[C("USER_AUTH_KEY")];
		$User = M('User');
		$anUser = $User->find($userid);
		$friend = $anUser['friend'];
	    $strUid=$userid;
       	if ($friend!="")
       	{
       		$strUid = $strUid.','.$friend;
       	}
		
		$Remind = M('Remind');
		$condition['uidTo']=$userid;
		$condition['dealTime']=0;
		$getRemind = $Remind->where($condition)->select();
		$remindNum = $Remind->where($condition)->count();
		$condition['type']=array('in','reply,reReply');
		$replyNum = $Remind->where($condition)->count();
		 
		$this->remindNum = $remindNum; //提醒总数
		$this->remind = $getRemind;  //提醒
		$this->replyNum = $replyNum;  //回复总数
		$this->user = $anUser; //用户
		$this->userid = $userid; //当前用户Id
		
		$Blog = M('Blog'); // 实例化Blog数据对象
	    import('ORG.Util.Page');// 导入分页类
	    $map['uidAuthor'] = array('in',$strUid);
	    $count = $Blog->where($map)->count();// 查询满足要求的总记录数
	    $Page = new Page($count,5);// 实例化分页类 传入总记录数
	    $Page->url = 'home';
	    // 进行分页数据查询 注意page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
	    $nowPage = isset($_GET['p'])?$_GET['p']:1;
	    $Model = New Model();
	    $list = $Model->table('think_blog blog,think_user user')
	    			  ->where('blog.uidAuthor in ('.$strUid.') and blog.uidAuthor = user.uid')
	    			  ->field('blog.*,user.username,user.photo,
	    			  	(select count(*) from think_blog where `bidForwardingFrom` 
	    			  	= blog.bid group by `bidForwardingFrom`) as numForwarding,
	    			  	(select count(*) from think_reply where `bid` = blog.bid
	    			  	 group by `bid`) as replyNum')
	    			  ->order('blog.btime desc')
	    			  ->page($nowPage.','.$Page->listRows)
	    			  ->select();
	    $show       = $Page->show();// 分页显示输出
	    $this->assign('count',$count);
	    $this->assign('page',$show);// 赋值分页输出
	    $this->assign('list',$list);// 赋值数据集
		
		$this->display();
		
	}
	
	public function doajaxfileupload(){  //异步上传图片
			ini_set("error_reporting","E_ALL & ~E_NOTICE");
			
			$userid=$_SESSION[C("USER_AUTH_KEY")];
			
			$error = "";
			$msg = "";
			$fileElementName = 'pic';
			if ((($_FILES["pic"]["type"] != "image/gif")
		&& ($_FILES["pic"]["type"] != "image/jpeg")
		&& ($_FILES["pic"]["type"] != "image/pjpeg")
		&& ($_FILES["pic"]["type"] != "image/bmp")
		&& ($_FILES["pic"]["type"] != "image/png"))
		|| ($_FILES["pic"]["size"] > 2000000)){
				$error="请选择2M以下的图片文件(gif,jpg,jpeg,bmp,png)";
				echo "{";
				echo				"error: '" . $error . "',\n";
				echo				"msg: '" . $msg . "'\n";
				echo "}";
				exit(0);
		}
			if(!empty($_FILES[$fileElementName]['error']))
			{
				switch($_FILES[$fileElementName]['error'])
				{
		
					case '1':
						$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
						break;
					case '2':
						$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
						break;
					case '3':
						$error = 'The uploaded file was only partially uploaded';
						break;
					case '4':
						$error = 'No file was uploaded.';
						break;
		
					case '6':
						$error = 'Missing a temporary folder';
						break;
					case '7':
						$error = 'Failed to write file to disk';
						break;
					case '8':
						$error = 'File upload stopped by extension';
						break;
					case '999':
					default:
						$error = 'No error code avaiable';
				}
			}elseif(empty($_FILES['pic']['tmp_name']) || $_FILES['pic']['tmp_name'] == 'none')
			{
				$error = 'No file was uploaded..';
			}else 
			{
					$extend = explode(".",$_FILES["pic"]["name"]);
				    $key = count($extend)-1;
				    $ext = ".".$extend[$key];
				    $newfile = $userid.$ext;
				    $newfileori = $userid."_ori".$ext;
				 
				    if(!file_exists('picture')){mkdir('picture');}
				    if (file_exists($newfile))
				    {
				      unlink($newfile);
				    }
					if (file_exists($newfileori))
				    {
				      unlink($newfileori);
				    }
				    move_uploaded_file($_FILES["pic"]["tmp_name"],"picture/" . $newfileori);
				    
				    require_once ('Lib/Model/image.php');
				    $img = new Image("picture/" . $newfileori);
				    $img->changeSize(300);//改变尺寸
					$img->create("picture/" . $newfile);
					$img->free();
					
					$msg = 'picture/'.$newfile;
					@unlink($_FILES['pic']);		
			}		
			echo "{";
			echo				"error: '" . $error . "',\n";
			echo				"msg: '" . $msg . "'\n";
			echo "}";
	}
	
	public function postBlog(){
		$userid=$_SESSION[C("USER_AUTH_KEY")];
		
		$Blog = M('Blog');
		$content = $_POST['blog'];
		$Blog->content = $content;
		$btime = time();
		$Blog->btime = $btime;
		$Blog->uidAuthor = $userid;
		$picture = $_POST['isPicUp'];
		if($picture!="")
		{
			$extend = explode(".",$picture);
		    $key = count($extend)-1;
		    $ext = ".".$extend[$key];
		    $pictureori = substr($picture,0,strrpos($picture,"."))."_ori".$ext;
		    $newfile = $userid."_".$btime.$ext;
		    $newfileori = $userid."_".$btime."_ori".$ext;
			rename($picture,"picture/".$newfile);
			rename($pictureori,"picture/".$newfileori);

			$picture="picture/".$newfile;
			$Blog->picture = $picture;
			$pictureori = "picture/".$newfileori;
			$picturesma = "picture/".$userid."_".$btime."_sma".$ext;					
		}
		
		if($Blog->add())
		{
			$User = M('User');
			$anUser = $User->find($userid);
			$photo = $anUser['photo'];
			$username = $anUser['username'];
			
			$aBlog=$Blog->order('bid desc')->limit(1)->select();
			$bid = $aBlog[0]['bid'];
			
			if($picture=="")
			{
				?>
				<div id="divBlogAll<?=$bid ?>" style="width:600px;">
				  <div style="width:50px;float:left;"><a href="profile.php?uid=<?=$userid ?>"><img src="<?=__APP__.'/'.$photo ?>" onload="resizeImage(this,50,50);" /></a></div>
				  <div style="text-align:left; padding-left: 0px; margin-left:70px;">
				  <div style="" id="contentBlog<?=$bid ?>"><p style="font-size:14px; color:#666;"><a href="profile.php?uid=<?=$userid ?>"><?=$username ?></a>：<?=$content ?></p></div>
				  <div style="margin-top:10px;"><div style=" display:inline-block;"><span style="font-size:12px;"><a href="blog.php?bid=<?=$bid ?>">发表于 <?=date("Y-m-d H:i:s",$btime) ?></a></span></div>
				  <div style=" float:right;">
				  <span style="font-size:12px;cursor:pointer;color:#69F;" id="delBlog<?=$bid ?>" onclick="delBlog('<?=$bid ?>')" >删除</span>
				  <span style="font-size:12px;color:#CCC;" >|</span>
				  <span style="font-size:12px;cursor:pointer;color:#69F;" id="forwardingBlog<?=$bid ?>" onclick="openLayer('forwardingBlog<?=$bid ?>','forwarding','');" >转发</span>
                  <span style="font-size:12px;color:#CCC;" >|</span>				  
				  <span id="replyNumBlog<?=$bid ?>" style="font-size:12px;cursor:pointer;color:#69F;" onclick="showReply(this,'Blog<?=$bid ?>');" >评论</span></div>
				  </div>
				  
				  <div id="replyBlog<?=$bid ?>" style="margin-top:10px; display:none;border:1px solid #CCC ;">
				  
				  <input type="text" id="textReplyBlog<?=$bid ?>" size="73"/><input id="buttonReplyBlog<?=$bid ?>" type="button" style="cursor:pointer;" value="评论" onclick="reply('<?=$bid ?>');" />
				  
				   <div id="replyContentBlog<?=$bid ?>" style="margin-top:10px; margin-left:10px; margin-right:10px;">
				  </div>
				  
				  </div>
				  </div> 
				</div>
				<hr id="hr<?=$bid ?>" style="border-top:0.5px dotted #CCC;" />							
				<?php
			}
			else 
			{	
				$arr=getimagesize($pictureori);
				
				?>
				<div id="divBlogAll<?=$bid ?>" style="width:600px;">
				  <div style="width:50px;float:left;"><a href="profile.php?uid=<?=$userid ?>"><img src="<?=__APP__.'/'.$photo ?>" onload="resizeImage(this,50,50);" /></a></div>
				  <div style="text-align:left; padding-left: 0px; margin-left:70px;">
				  <div style="" id="contentBlog<?=$bid ?>"><p style="font-size:14px; color:#666;"><a href="profile.php?uid=<?=$userid ?>"><?=$username ?></a>：<?=$content ?></p></div>
				  <div id="divBlog<?=$bid ?>" style="overflow:hidden;cursor:pointer;"><img style="border:2px double #CCC;cursor:pointer;" id="imgBlog<?=$bid ?>" src="<?=__APP__.'/'.$picture ?>" onload="resizeImage(this,300,300);" onclick="showLarge('Blog<?=$bid ?>');" />
				  </div>
				  <div style="margin-top:10px;"><div style=" display:inline-block;"><span style="font-size:12px;"><a href="blog.php?bid=<?=$bid ?>">发表于 <?=date("Y-m-d H:i:s",$btime) ?></a></span></div>
				  <div style=" float:right;">
				  <span style="font-size:12px;cursor:pointer;color:#69F;" id="delBlog<?=$bid ?>" onclick="delBlog('<?=$bid ?>')" >删除</span>
				  <span style="font-size:12px;color:#CCC;" >|</span>
				  <span style="font-size:12px;cursor:pointer;color:#69F;" id="forwardingBlog<?=$bid ?>" onclick="openLayer('forwardingBlog<?=$bid ?>','forwarding','');" >转发</span>
                  <span style="font-size:12px;color:#CCC;" >|</span>				  
				  <span id="replyNumBlog<?=$bid ?>" style="font-size:12px;cursor:pointer;color:#69F;" onclick="showReply(this,'Blog<?=$bid ?>');" >评论</span></div>
				  
				  </div>
				  <div id="replyBlog<?=$bid ?>" style="margin-top:10px; display:none;  border:1px solid #CCC ;">
				  <input type="text" id="textReplyBlog<?=$bid ?>" size="73"/><input id="buttonReplyBlog<?=$bid ?>" type="button" style="cursor:pointer;" value="评论" onclick="reply('<?=$bid ?>');" />
				  <div id="replyContentBlog<?=$bid ?>" style="margin-top:10px; margin-left:10px; margin-right:10px;">
				  </div>
				  </div>
				  <input type="hidden" id="hidBlog<?=$bid ?>" value="<?=$arr[0] ?>,<?=$arr[1] ?>,<?=__APP__.'/'.$pictureori ?>" />
				  </div>
				</div>
				<hr id="hr<?=$bid ?>" style="border-top:0.5px dotted #CCC;" />		
				<?php
			}
		} else {
			//echo '抱歉！添加数据失败：',mysql_error(),'<br />';
			echo "发布失败";
		}
	
	}
	
	public function getReply(){
		$bid = $_GET['bid'];
		$Reply = M('Reply');
		$map['bid'] = $bid;
		$count = $Reply->where($map)->count();// 查询满足要求的总记录数
		$nowPage = isset($_GET['p'])?$_GET['p']:1;
		$Model = new Model();
		$getReply = $Model->table('think_reply reply,think_user user')
					->where('reply.bid='.$bid.' and reply.uidAuthor = user.uid')
					->field('reply.replyid,reply.uidAuthor,reply.content,reply.rtime,user.photo,user.username')
					->order('rtime desc')->limit(($nowPage-1)*10,10)->select();
		//echo '{"html":"';
		for($i=0;$i<count($getReply);$i++){
			?>
		  <div style="width:30px;float:left;overflow:hidden;"><a href="profile.php?uid=<?=$getReply[$i]['uidAuthor'] ?>">
		  <img src="<?=__APP__.'/'.$getReply[$i]['photo'] ?>" width="30" height="30" /></a></div>
		  <div style=" margin-left:40px;"><p style="font-size:12px; color:#666;">
		  <a href="profile.php?uid=<?=$getReply[$i]['uidAuthor'] ?>"><?=$getReply[$i]['username'] ?></a>
		  	：<?=$getReply[$i]['content'].' '?>(<?=date("Y-m-d H:i:s",$getReply[$i]['rtime']) ?>)</p></div>
		  <div style="text-align:right; font-size:12px;">
		  <span style=" margin-right:10px;cursor:pointer;color:#69F;" 
		  onclick="reReply('<?=$bid ?>','<?=$getReply[$i]['replyid'] ?>','<?=$getReply[$i]['username'] ?>');">
		  回复</span></div>
		  <hr style="border-top:0.5px dotted #CCC;" />
		  <?php	
		}
		$sumPage = (int)(($count-1)/10+1);
		if($sumPage<=1){ //每页十条信息
			echo '<div style="text-align:right;">共 '.$count.' 条回复，第 '.$sumPage.' 页，共 '.$sumPage.' 页</div>';	
		}
		elseif ($nowPage == 1){
			echo '<div style="text-align:right;">共 '.$count.' 条回复，第 '.$nowPage.' 页，共 '.$sumPage.' 页  ';
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.$nowPage.')">'.' '.$nowPage.'</span>';
			for($i=$nowPage+1;$i<=$nowPage+4&&$i<=$sumPage;$i++)
				echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.$i.')">'.' '.$i.'</span>';
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.($nowPage+1).')">'.' 下一页</span>';
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.$sumPage.')">'.' 最后一页</span>';
			echo '</div>';
		}
		elseif ($nowPage == $sumPage){
			echo '<div style="text-align:right;">共 '.$count.' 条回复，第 '.$nowPage.' 页，共 '.$sumPage.' 页  ';
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.',1)">'.' 第一页</span>';			
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.($nowPage-1).')">'.' 上一页</span>';
			$begin=($nowPage-4)>0?$nowPage-4:1;
			for($i=$begin;$i<=$nowPage;$i++)
				echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.$i.')">'.' '.$i.'</span>';
			echo '</div>';			
		}
		else{
			$begin = $nowPage-$nowPage%5+1;
			$end = $begin+4;
			
			echo '<div style="text-align:right;">共 '.$count.' 条回复，第 '.$nowPage.' 页，共 '.$sumPage.' 页  ';
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.$sumPage.')">'.' 第一页</span>';			
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.($nowPage+1).')">'.' 上一页</span>';
			for($i=$begin;$i<=$end&&$i<=$sumPage;$i++)
				echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.$i.')">'.' '.$i.'</span>';
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.($nowPage+1).')">'.' 下一页</span>';
			echo '<span style="color:blue;cursor:pointer;" onmouseout="this.style.textDecoration=\'none\'" 
					onmouseover="this.style.textDecoration=\'underline\'" onclick="getReply('.$bid.','.$sumPage.')">'.' 最后一页</span>';				
			echo '</div>';
		}
		
		echo '-'.$count;
	    
	}
	
	public function reply(){
	
		$userid=$_SESSION[C('USER_AUTH_KEY')];
		
		$bid = $_POST['bid'];
		$content = $_POST['content'];
		$rtime = time();
		
		$Reply = M('Reply');
		$Reply->bid = $bid;
		$Reply->uidAuthor = $userid;
		$Reply->content = $content;
		$Reply->rtime = $rtime;
		if($Reply->add()){
			$getReplyId = $Reply->field('replyid')->order('replyid desc')->limit(1)->select();
			$replyid = $getReplyId[0]['replyid'];
			
			$Blog = M('Blog');
			$aBlog = $Blog->find($bid);
			$uidTo = $aBlog['uidAuthor'];
			
			$Remind = M('Remind');
			$Remind->type = 'reply';
			$Remind->uidFrom = $userid;
			$Remind->bid = $bid;
			$Remind->replyid = $replyid;
			$Remind->rtime = $rtime;
			
			if($uidTo==$userid?1:$Remind->add()){
				$User = M('User');
				$aUser = $User->find($userid);
				?>
			  <div style="width:30px;float:left;overflow:hidden;"><a href="profile.php?uid=<?=$userid ?>"><img src="<?=__APP__.'/'.$aUser['photo'] ?>" width="30" height="30" /></a></div>
			  <div style=" margin-left:40px;"><p style="font-size:12px; color:#666;"><a href="profile.php?uid=<?=$userid ?>"><?=$aUser['username'] ?></a>：<?=$content ?>(<?=date("Y-m-d H:i:s",$rtime) ?>)</p></div>
			  <div style="text-align:right; font-size:12px;"><span style=" margin-right:10px;cursor:pointer;color:#69F;" onclick="reReply('<?=$bid ?>','<?=$replyid ?>','<?=$aUser['username'] ?>');" >回复</span></div>
			  <hr style="border-top:0.5px dotted #CCC;" />				
				<?php 
			}
			else {
				echo '评论失败';
			}
		}
		else {
			echo '评论失败';
		}
	}
	
}